<?php
/**
 * @author GhostWei
 * @date Sep 5, 2012
 */
class controller_admin_picture_import extends system_user_controller_panel {
	
	private $fromLang = null;
	public function init() {
		if(!parent::init()) {
			return ;
		}
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Pictures'))->setRoute('picture/index'));
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Import'))->setRoute('picture/import/index'));
		if($this->getRequest()->isPost()) {
			$this->view->referer = $this->_post('referer');
		}
		$this->fromLang = trim($this->_post('lang'));
		if(!$this->fromLang) {
			$this->render('picture/import/selectLang.phtml');
			return;
		}
		picture_category::$_lang = $this->fromLang;
		$this->view->fromLang = $this->fromLang;
	}
	
	public function action_special() {
		if(!$this->fromLang) {
			return;
		}
		$specialList = array();
		$render = null;
		if($this->getRequest()->isPost() && $this->_post('submit') == 'select') {
			try {
				$selectedId = (array) $this->_post('special_id');
				if(empty($selectedId)) {
					throw new picture_exception('No Item Slected');
				}

				$render = 'picture/import/specialImport.phtml';
				$ids = implode(',', $selectedId);
				$concept = new picture_special_concept($this->fromLang);
				$specialList = $concept->fetchAll(array("special.id IN($ids)"));
				
				if($this->_post('import') == '1') {
					$this->view->data = $data = (array) $this->_post('data');
					$lConcept = new picture_special_localeConcept($this->user->getLang());
					try {
						system_db::getAdapter()->beginTransaction();
						foreach($specialList AS $special) {
							if(!isset($data[$special->getId()])) continue;
							if(!($row = $lConcept->fetch(array('special.id = ?' => $special->getId())))) continue;
							
							$_data = $data[$special->getId()];
							$row->getLocale()->setTitle(trim($_data['title']));
							$row->getLocale()->setDescription($_data['description']);
							$row->setKeywords(trim($_data['tag']));	
							foreach((array) $this->_post('category_id') AS $cid) {
								$row->addCategoryList($cid);
							}
							$row->save();
						}
						system_db::getAdapter()->commit();
						$this->view->throwMessage = 'Complete';
					} catch (Exception $e) {
						system_db::getAdapter()->rollBack();
						$this->view->throwException = $e;
					}
				}
			
			} catch (Exception $e) {
				$this->view->throwException = $e;
			}
		}
		$this->view->specialList = $specialList;
		$this->render($render);
	}
		
	public function action_index() {
		$this->render();
	}
	
}
